package LibDL.data;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@BenchmarkMode(Mode.AverageTime)
@State(Scope.Thread)
public class InteractionsBM {

    private String train_root;
    private String test_root;

    @Setup
    public void setup() {
        train_root = System.getProperty("user.dir")
                + "/benchmark/src/main/resources/ml1m/debug/train.txt";
        test_root = System.getProperty("user.dir")
                + "/benchmark/src/main/resources/ml1m/debug/test.txt";
    }

    @Benchmark
    public String split() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(new File(train_root)));
        String line, out = "";
        while ((line = br.readLine()) != null) {
            out = line.split(" ")[1];
        }
        br.close();
        return out;
    }

    @Benchmark
    public String StringTokenizer() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(new File(train_root)));
        String line, out = "";
        while ((line = br.readLine()) != null) {
            StringTokenizer token = new StringTokenizer(line," ");
            token.nextToken();
            out = token.nextToken();
        }
        br.close();
        return out;
    }

    @Benchmark
    public String matcher() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(new File(train_root)));
        String line, out = "";
        Pattern p = Pattern.compile("\\S+");
        Matcher m;
        while ((line = br.readLine()) != null) {
            m = p.matcher(line);
            if (m.find()) {
                out = line.substring(m.start(), m.end());
            }
            if (m.find()) {
                out = line.substring(m.start(), m.end());
            }
        }
        br.close();
        return out;
    }
    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(InteractionsBM.class.getSimpleName())
                .timeout(TimeValue.valueOf("30s"))
                .forks(1)
                .warmupIterations(6)
                .warmupTime(TimeValue.valueOf("3s"))
                .measurementIterations(5)
                .measurementTime(TimeValue.valueOf("10s"))
                .build();
        new Runner(options).run();
    }
}
